<?php

namespace app\admin\controller\dts\config;

use app\common\controller\Backend;
use BarcodeBakery\Common\BCGFontFile;
use BarcodeBakery\Common\BCGColor;
use BarcodeBakery\Common\BCGDrawing;
use BarcodeBakery\Barcode\BCGcode128;
use think\Db;
use OSS\OssClient;
/**
 * 巡检二维码管理
 *
 * @icon fa fa-circle-o
 */
class Barcode extends Backend
{
    protected $noNeedRight = ['selectpage'];
    /**
     * Barcode模型对象
     * @var \app\admin\model\dts\config\Barcode
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\config\Barcode;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function selectpage() {
        return parent::selectpage();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add() {

        if($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if($params) {

                require_once(EXTEND_PATH.'phpqrcode/phpqrcode.php');
                $errorCorrectionLevel = 'L'; // 纠错级别：L、M、Q、H
                $matrixPointSize = 6; // 点的大小：1到10

                //打开缓冲区
                ob_start();

                for($i=0; $i<$params['quantity']; $i++) {
                    $identifier = uniqid('P');

                    if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) {
                        $errorCorrectionLevel = $qrLevel;
                    }
                    if (isset($qrSize)) {
                        $matrixPointSize = min(max((int)$qrSize, 1), 10);
                    }

                    // 生成的文件名
                    $fileurl = '/barcode/'.$identifier.'.png';
                    $filePath = ROOT_PATH . 'public' . $fileurl;
                    \Qrcode::png($identifier, $filePath, $errorCorrectionLevel, $matrixPointSize, 2);

                    $config = get_addon_config('alioss');
                    $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
                    
                    try {
                        $ret = $oss->uploadFile($config['bucket'], ltrim($fileurl, "/"), $filePath);
                        $this->model->create(['identifier' => $identifier, 'fileurl' => $ret['info']['url'], 'createby' => $this->auth->nickname]);
                    }catch(\Exception $e) {
                        \think\Log::write($e->getMessage());
                    }
                }    
                //会清除缓冲区的内容，并将缓冲区关闭，但不会输出内容。
                ob_end_clean();
                $this->success('创建成功');
            }   
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }
   
    public function download()
    {

        $tmpDir =  ROOT_PATH . 'tmp'; //产生一个临时文件，用于缓存下载文件
        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }

        //----------开始------------
        $filename = '二维码图片' . date("Y-m-d H:i", time()) . '.zip'; //下载的默认文件名
        $zipNameUrl = $tmpDir .'/'. $filename; // 文件路径

        // 生成文件
        $zip = new \ZipArchive();
        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
        }

        $where = [];
        $params = $this->request->get('params');
        if($params) {
            $query = json_decode($params, true);
            if(isset($query['ids']) && $query['ids']) {
                $where = ['id' => ['in', $query['ids']]];
            }else {
                if(isset($query['filter'])) {
                    $filter = json_decode($query['filter'], true);
                    if(isset($filter['createtime'])) {
                        $time = explode(' - ', $filter['createtime']);
                        $filter['createtime'] = ['between' => [$time[0], $time[1]]];
                    }
                    $where = $filter;
                }
            }
        }

        //获取图片
        $list = Db::name('dts_config_barcode')->field('fileurl,identifier')->where($where)->select();

        foreach ($list as $v) {
            $fileurl = str_replace('http://', '', $v['fileurl']);
            $fileurl = str_replace('https://', '', $fileurl);
            $fileurl = str_replace('dts-file.oss-cn-beijing.aliyuncs.com', '', $fileurl);

            $file = ROOT_PATH . 'public' . $fileurl;
            $isFile = file_exists($file);
            if ($isFile) {
                //抓取图片内容
                $fileContent = file_get_contents($file);
                //添加图片
                $zip->addFromString(basename($file), $fileContent);
            }
        }
        //----------关闭------------
        $zip->close();

        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:' . gmdate('D, d M Y H:i:s') . 'GMT');
        header("Content-Description: File Transfer");
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-type:application/zip');
        header('Content-Disposition:attachment; filename="' . $filename . '"'); //设置下载的默认文件名
        header('Content-length:' . filesize($zipNameUrl));

        @flush();
        @ob_flush();

        @readfile($zipNameUrl);
        @unlink($zipNameUrl);

        exit();
    }
}
